package com.web;

import com.MybatisUtil.MybatisUtil;
import com.MybatisUtil.StringUtil;
import com.bean.Category;
import com.bean.News;
import com.dao.CategoryMapper;
import com.dao.NewsMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@WebServlet(urlPatterns = "/news")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String op = req.getParameter("op");
        if("list".equals(op)) {
            list(req,resp);
        }else if("find".equals(op)){
            find(req,resp);
        }else {
            throw new ServletException("不支持的操作！");
        }
    }
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NewsMapper newsDao = MybatisUtil.getMapper(NewsMapper.class);
        //List<News> list = newsDao.findAllNoTransWithUsers();
        CategoryMapper categoryDao = MybatisUtil.getMapper(CategoryMapper.class);
        Map<String,Object> params = new HashMap<>();
        //String keywords = StringUtil.getString(req,"keywords");
        StringUtil.getParameters(req,
                new String[]{"keywords","category_id"},params);
        /*StringUtil.getInterval(req,
                new String[]{"interval","startTime","endTime"},params);*/
        StringUtil.getInterval(req,"interval","startTime","endTime",params);
        //params.put("keywords",keywords);

        List<News> list = newsDao.find(params);
        //分类
        List<Category> categorys = categoryDao.findAll();
        req.setAttribute("params",params);
        req.setAttribute("list",list);
        req.setAttribute("categorys",categorys);
        req.getRequestDispatcher("/news/list.jsp").forward(req,resp);
    }
    private void find(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int newsId = StringUtil.getInt(req,"id");
        NewsMapper newsDao = MybatisUtil.getMapper(NewsMapper.class);
        News news = newsDao.findNewsWithReplys(newsId);
        req.setAttribute("news",news);
        req.getRequestDispatcher("/news/detail.jsp").forward(req,resp);
    }
}

